package com.springboot.java.design.proxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @Author: TongRui乀
 * @Date: 2020-07-01 10:29
 * @description： 测试动态代理  CGLIB
 */
public class TestCglib {

    public static void main(String[] args) {

        GrateWallCar car = new GrateWallCar();
        // 代理类
        CGlibProxy proxy = new CGlibProxy(car);
        // 代理对象创建类
        Enhancer enhancer = new Enhancer();
        // 设置被代理类
        enhancer.setSuperclass(car.getClass());
        // 设置代理类
        enhancer.setCallback(proxy);
        // 生成代理对象
        GrateWallCar proxyCar = (GrateWallCar) enhancer.create();

        proxyCar.run();
    }

}

/**
 *  CGLib 实现的动态代理类
 */
class CGlibProxy implements MethodInterceptor {

    private Object target;

    CGlibProxy(Object target){
        this.target = target;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

        System.out.println("进入代理方法");

        return methodProxy.invokeSuper(o, objects);
    }
}
